package com.bxx.ermall.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bxx.ermall.common.lang.Result;
import com.bxx.ermall.entity.Goods;
import com.bxx.ermall.service.GoodsService;
import com.bxx.ermall.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author buxiaoxing
 * @since 2021-02-02
 */
@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @PostMapping("/goods/addUpdate")
    @RequiresAuthentication
    public Result add(@Validated @RequestBody Goods goods){
        Goods temp = null;
        if(goods.getId() != null){
            temp = goodsService.getById(goods.getId());
        }else {
            temp = new Goods();
            temp.setState(1);
            temp.setOwner(ShiroUtil.getProfile().getId());
        }
        BeanUtil.copyProperties(goods,temp,"state","id","owner");
        goodsService.saveOrUpdate(temp);
        return Result.succ(null);
    }

    @PostMapping("/goods/delete")
    @RequiresAuthentication
    public Result delete(@Validated @RequestBody String data){
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = (Integer)jsonObject.get("id");
        goodsService.removeById(id);
        return Result.succ(null);
    }


    @GetMapping("/goods/list")
    @RequiresAuthentication
    public Result list(){
        Integer owner = ShiroUtil.getProfile().getId();
        List<Goods> data = goodsService.list(new QueryWrapper<Goods>().eq("owner", owner));
        return Result.succ(data);
    }


}

